<script setup lang="tsx">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { watch, inject, reactive, Ref, ref, unref } from 'vue'
import { Table } from '@/components/Table'
import {
  Row,
  getListAreaApi,
  createAreaApi,
  delAreaApi,
  getListStorageApi,
  createStorageApi,
  delStorageApi,
  moveStorageApi
} from '@/api/warehouse'
import { useTable } from '@/hooks/web/useTable'
import { BaseButton } from '@/components/Button'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { searchStorageCateApi } from '@/api/utils/search'
import {
  ElContainer,
  ElAside,
  ElMain,
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElSelect,
  ElOption,
  FormInstance
} from 'element-plus'
const emit = defineEmits(['close', 'get-list'])
const currentRow: Ref<Row> = inject('currentRow') as Ref<Row>
const dialogFormVisible = ref(false)
const form = reactive({
  line: '',
  row: '',
  layer: ''
})
const toggleDialog = () => {
  dialogFormVisible.value = true
}
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'name',
    label: '库区'
  },
  {
    field: 'action',
    label: '操作',
    table: {
      slots: {
        default: ({ row }) => {
          return (
            <>
              <BaseButton type="warning" onClick={() => toggleDialog()}>
                分库位
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(row)}>
                删除
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])
// 库区
const { allSchemas } = useCrudSchemas(crudSchemas)
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListAreaApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      warehouse_id: currentRow.value.id
    })
    return {
      list: res.data.list,
      total: res.data.count
    }
  },
  fetchDelApi: async () => {
    const res = await delAreaApi({ id: unref(ids).join(',') })
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const delLoading = ref(false)

const delData = async (row: Row | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: Row) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const warehouse_area_id = ref()
const handleCurrentChange = (val) => {
  warehouse_area_id.value = val.id || ''
  getList1()
}
// --
// 库位
const TableSchema = reactive<CrudSchema[]>([
  {
    field: 'name',
    label: '库位码'
  },
  {
    field: 'warehouse_area_name',
    label: '所属库区'
  },
  {
    field: 'quantity',
    label: '货物数量'
  },
  {
    field: 'action',
    width: '260px',
    label: '操作',
    table: {
      slots: {
        default: ({ row }) => {
          if (row.quantity > 0) {
            return (
              <>
                <BaseButton type="primary" onClick={() => move(row)}>
                  移位
                </BaseButton>
              </>
            )
          } else {
            return (
              <>
                <BaseButton type="primary" onClick={() => delData1(row)}>
                  删除
                </BaseButton>
              </>
            )
          }
        }
      }
    }
  }
])
// 移位
const dialogFormVisibleed = ref(false)
const oldId = ref('')
const move = (row) => {
  getListApidata(row.warehouse_area_id)
  oldId.value = row.id
  dialogFormVisibleed.value = true
}
const options = ref<Array<{ name: string; id: number }>>([])
const getListApidata = async (id) => {
  const res = await searchStorageCateApi({
    warehouse_area_id: id,
    field: 'id,name,warehouse_area_id'
  })
  options.value = res.data.list
}
const new_warehouse_storage_id = ref<string[]>([])
const moveSubmitForm = async () => {
  try {
    if (new_warehouse_storage_id.value) {
      const params = {
        new_warehouse_storage_id: new_warehouse_storage_id.value,
        id: oldId.value
      }
      const res = await moveStorageApi(params)
      if (res) {
        ElMessage.success(res.msg)
        dialogFormVisibleed.value = false
        new_warehouse_storage_id.value = []
        oldId.value = ''
        getList1()
      }
    } else {
      ElMessage('请选择新库位!')
    }
  } catch (err) {
    console.log(err)
  }
}
// 表列表
const { allSchemas: allSchemas1 } = useCrudSchemas(TableSchema)
const idsed = ref<string[]>([])
const {
  tableRegister: tableRegister1,
  tableState: tableState1,
  tableMethods: tableMethods1
} = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState1
    const res = await getListStorageApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      warehouse_id: currentRow.value.id,
      warehouse_area_id: warehouse_area_id.value
    })
    return {
      list: res.data.list,
      total: res.data.count
    }
  },
  fetchDelApi: async () => {
    const res = await delStorageApi({ id: unref(idsed).join(',') })
    return !!res
  }
})
const {
  loading: loading1,
  dataList: dataList1,
  total: total1,
  currentPage: currentPage1,
  pageSize: pageSize1
} = tableState1
const { getList: getList1, getElTableExpose: getElTableExpose1, delList: delList1 } = tableMethods1
const delLoading1 = ref(false)

const delData1 = async (row: Row | null) => {
  const elTableExpose = await getElTableExpose1()
  idsed.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: Row) => v.id) || []
  delLoading1.value = true
  await delList1(unref(idsed).length).finally(() => {
    delLoading1.value = false
  })
}
// --
const open = () => {
  ElMessageBox.prompt('', '新增库区', {
    confirmButtonText: '创建',
    cancelButtonText: '关闭',
    inputPlaceholder: '请输入库区名称'
  })
    .then(async ({ value }) => {
      const res = await createAreaApi({ name: value, warehouse_id: currentRow.value.id })
      if (res) {
        ElMessage.success(res.msg)
        getList()
      }
    })
    .catch(() => {})
}
const formRef = ref<FormInstance>()
const disabled = ref(false)
const submitForm = async () => {
  try {
    const valid = await formRef.value?.validate().catch((err) => console.log(err))
    if (valid) {
      disabled.value = true
      const params = {
        ...form,
        warehouse_id: currentRow.value.id,
        warehouse_area_id: warehouse_area_id.value
      }
      const res = await createStorageApi(params)
      if (res) {
        ElMessage.success(res.msg)
        dialogFormVisible.value = false
        disabled.value = false
        form.layer = ''
        form.line = ''
        form.row = ''
        getList1()
      }
    }
  } catch (err) {
    disabled.value = false
    console.log(err)
  }
}
watch(
  () => currentRow.value,
  (currentRow) => {
    if (!currentRow) return
    getList()
    getList1()
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <ContentDetailWrap title="分仓库详情">
    <ElContainer>
      <ElAside width="500px">
        <BaseButton type="primary" style="margin-bottom: 20px" @click="open">创建库区</BaseButton>
        <Table
          v-model:pageSize="pageSize"
          v-model:currentPage="currentPage"
          :columns="allSchemas.tableColumns"
          :data="dataList"
          :loading="loading"
          :pagination="{
            total
          }"
          @register="tableRegister"
          @current-change="handleCurrentChange"
        />
        <!-- 库位 -->
        <ElDialog v-model="dialogFormVisible" title="新增库位" width="500">
          <ElForm :model="form" ref="formRef">
            <ElFormItem
              label="行数"
              prop="line"
              required
              :rules="[
                { required: true, message: '不能为空' },
                { pattern: /^[1-9]\d*$/, message: '只允许阿拉伯正整数' }
              ]"
            >
              <ElInput v-model="form.line" placeholder="请输入（不能为空，只允许阿拉伯正整数）" />
            </ElFormItem>
            <ElFormItem
              label="列数"
              prop="row"
              required
              :rules="[
                { required: true, message: '不能为空' },
                { pattern: /^[1-9]\d*$/, message: '只允许阿拉伯正整数' }
              ]"
            >
              <ElInput v-model="form.row" placeholder="请输入（不能为空，只允许阿拉伯正整数）" />
            </ElFormItem>
            <ElFormItem
              label="层数"
              prop="layer"
              required
              :rules="[
                { required: true, message: '不能为空' },
                { pattern: /^[1-9]\d*$/, message: '只允许阿拉伯正整数' }
              ]"
            >
              <ElInput v-model="form.layer" placeholder="请输入（不能为空，只允许阿拉伯正整数）" />
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="dialogFormVisible = false">关闭</ElButton>
              <ElButton type="primary" @click="submitForm()" :disabled="disabled">创建</ElButton>
            </div>
          </template>
        </ElDialog>
      </ElAside>
      <ElMain>
        <Table
          v-model:pageSize="pageSize1"
          v-model:currentPage="currentPage1"
          :columns="allSchemas1.tableColumns"
          :data="dataList1"
          :loading="loading1"
          :pagination="{
            total: total1
          }"
          @register="tableRegister1"
        />
        <!-- 移位 -->
        <ElDialog v-model="dialogFormVisibleed" title="温馨提示" width="500">
          <div style="margin-bottom: 30px"
            >该操作不可逆，删除后对应商品自动分配到其余的库位中，你是否确定要删除？</div
          >
          <ElForm>
            <ElFormItem
              label="请选择需要移至的库位"
              prop="line"
              :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]"
            >
              <ElSelect
                v-model="new_warehouse_storage_id"
                filterable
                remote
                reserve-keyword
                placeholder="请选择"
                style="width: 240px"
              >
                <ElOption
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </ElSelect>
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="dialogFormVisibleed = false">关闭</ElButton>
              <ElButton type="primary" @click="moveSubmitForm()">确定</ElButton>
            </div>
          </template>
        </ElDialog>
      </ElMain>
    </ElContainer>

    <template #footer>
      <div class="w-full flex items-center justify-center">
        <BaseButton @click="emit('close')">返回</BaseButton>
      </div>
    </template>
  </ContentDetailWrap>
</template>
